﻿using System;
using System.Linq;
using System.Linq.Expressions;
using Sharp.Portal.Other;

namespace Sharp.Portal.Mvc.List
{
    public partial class SharpListHelper<TEntity>
    {

        #region 从ColumnItem生成QueryItem对象
        /// <summary>
        /// 从ColumnItem生成QueryItem对象
        /// </summary>
        /// <param name="path">表达式</param>
        public QueryItem CopyToQueryItem<TProperty>(Expression<Func<TEntity, TProperty>> path)
        {
            string propertyname;
            LambdaHelper.TryParsePath(path.Body, out propertyname);

            return CopyToQueryItem(propertyname);
        }

        /// <summary>
        /// 从ColumnItem生成QueryItem对象
        /// </summary>
        /// <param name="propertyname">实体属性</param>
        public QueryItem CopyToQueryItem(string propertyname)
        {
            ColumnItem columnItem = Parent.ColumnItems.FirstOrDefault(x => x.Name == propertyname);

            return CopyToQueryItem(columnItem);
        }
        /// <summary>
        /// 从ColumnItem生成QueryItem对象
        /// </summary>
        /// <param name="columnItem">数据列表的列</param>
        public QueryItem CopyToQueryItem(ColumnItem columnItem)
        {
            if (columnItem == null)
            {
                return null;
            }
            if (columnItem.Hidden)
            {
                return null;
            }
            if (!columnItem.QueryFeatureOption.HasFlag(QueryFeature.Queryable))
            {
                return null;
            }
            Parent.QueryItems.Add(new QueryItem(columnItem));
            if (!columnItem.DataIndex.IsNullOrEmpty())
            {
                Parent.QueryItems.Last().Name = columnItem.DataIndex;
            }
            return Parent.QueryItems.Last();
        }
        #endregion

        public QueryItem AddQueryItem<TProperty>(Expression<Func<TEntity, TProperty>> path)
        {

            string propertyname;
            LambdaHelper.TryParsePath(path.Body, out propertyname);

            var column = new QueryItem();
            column.Name = propertyname;
            column.Bind = path.Body;
            column.DataType = path.Body.Type;
            column.QueryFeatureOption |= QueryFeature.Queryable;

            if (Parent.QueryItems.Any(q => q.Name == propertyname))
            {
                Parent.QueryItems.RemoveAll(r => r.Name == propertyname);
            }
            Parent.QueryItems.Add(column);

            return column;
        }
    }
}